package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.System;
import com.cskaoyan.bean.admin.vo.UpdateGoodsVo;
import com.cskaoyan.bean.admin.vo.*;
import com.cskaoyan.bean.vo.HotListNumsVO;
import com.cskaoyan.bean.wx.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.GoodsService;
import com.cskaoyan.utils.CommonUtil;
import com.cskaoyan.utils.HotGoodsSortUtil;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    AttributeMapper attributeMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    SpecificationMapper specificationMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    GrouponMapper grouponMapper;

    @Autowired
    AdMapper adMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    TopicMapper topicMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Autowired
    SystemMapper systemMapper;

    @Autowired
    CommentMapper commentMapper;

    @Override
    public BasePageData selectGoodsCount(Integer goodsId, String goodsSn, String name, BaseParam param) {
        //如果为0则全部查询
        if (param.getPage() != null) {
            PageHelper.startPage(param.getPage(), param.getLimit());
        }
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        if (goodsId != null && !"".equals(goodsId)) {
            criteria.andIdEqualTo(goodsId).andDeletedEqualTo(false);
        }

        if (goodsSn != null && !"".equals(goodsSn)) {
            criteria.andGoodsSnEqualTo(goodsSn).andDeletedEqualTo(false);
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        criteria.andDeletedEqualTo(false);

        if (param.getOrder() != null && param.getSort() != null) {
            goodsExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        }
        List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);

        if (param.getPage() == null) {
            return BasePageData.ok(goods);
        }
        return BasePageData.ok1(goods);
    }

    @Override
    public CatAndBrandVo selectCategory() {


        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andLevelEqualTo("L1").andDeletedEqualTo(false);
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

//        CategoryExample categoryExample1 = new CategoryExample();
//        CategoryExample.Criteria criteria1 = categoryExample1.createCriteria();
//        criteria1.andLevelEqualTo("L2").andDeletedEqualTo(false);
//        List<Category> categories1 = categoryMapper.selectByExample(categoryExample1);

        List<CategoryListVo> categoryListVos = new ArrayList<>();

//        for (Category category : categoryList) {
//            for (Category category1 : categories1) {
//                if (category.getId().equals(category1.getPid())){
//                    childrenVos.add(new ChildrenVo(category1.getId() , category1.getName()));
//                }
//            }
//            categoryListVos.add(new CategoryListVo(category.getId() , category.getName() , childrenVos));
//        }
        for (Category category : categoryList) {
            List<ChildrenVo> childrenVos = new ArrayList<>();
            Integer id = category.getId();
            String name = category.getName();
            CategoryExample categoryExample2 = new CategoryExample();
            CategoryExample.Criteria criteria2 = categoryExample2.createCriteria();
            criteria2.andPidEqualTo(id).andDeletedEqualTo(false);
            List<Category> categories = categoryMapper.selectByExample(categoryExample2);
            for (Category category1 : categories) {
                Integer category1Id = category1.getId();
                String name1 = category1.getName();
                childrenVos.add(new ChildrenVo(category1Id, name1));
            }
            categoryListVos.add(new CategoryListVo(id, name, childrenVos));
        }

        List<BrandListVo> brandListVos = new ArrayList<>();
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria criteria2 = brandExample.createCriteria();
        criteria2.andDeletedEqualTo(false);
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        for (Brand brand : brands) {
            brandListVos.add(new BrandListVo(brand.getId(), brand.getName()));
        }

        CatAndBrandVo catAndBrandVo = new CatAndBrandVo(categoryListVos, brandListVos);
        return catAndBrandVo;
    }

    @Override
    public void addGoods(CreateGoodsVo goods) {


        Goods goods1 = goods.getGoods();
        String goodsSn = goods1.getGoodsSn();
        int id = Integer.parseInt(goodsSn);
//        goods1.setId(id);
        goods1.setAddTime(new Date());
        goods1.setUpdateTime(new Date());
        goodsMapper.insertSelective(goods1);

        List<Attribute> attributes = goods.getAttributes();
        for (Attribute attribute : attributes) {
            attribute.setGoodsId(id);
            attribute.setAddTime(new Date());
            attribute.setUpdateTime(new Date());
            attributeMapper.insertSelective(attribute);
        }

        List<Product> products = goods.getProducts();
        for (Product product : products) {
            product.setGoodsId(id);
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            productMapper.insertSelective(product);
        }

        List<Specification> specifications = goods.getSpecifications();
        for (Specification specification : specifications) {
            specification.setGoodsId(id);
            specification.setAddTime(new Date());
            specification.setUpdateTime(new Date());
            specificationMapper.insertSelective(specification);
        }
    }


    @Override
    public void updateGoods(HttpServletRequest req, UpdateGoodsVo goods) {

        ServletContext servletContext = req.getServletContext();
        Object hotList = servletContext.getAttribute("hotList");
        if(hotList != null){
            ArrayList<HotListNumsVO> hotListNumsVOS = (ArrayList<HotListNumsVO>) hotList;
            Integer targetId = goods.getGoods().getId();
            int created = 1;
            for (HotListNumsVO vo : hotListNumsVOS) {
                if(targetId.equals(vo.getGoods().getId())){ // 匹配到了，说明是原先热卖商品
                    if(!goods.getGoods().getIsHot()){   // 如果准备修改成非热卖，就在Context中删除掉
                        hotListNumsVOS.removeIf((tmp) -> tmp.getGoods().getId().equals(goods.getGoods().getId()));
                        created = 0;    // 标记不是在Context中新增
                        break;
                    }
                    // 如果仍然是热卖的，就什么都不做
                }
            }
            if(created == 1){   // 如果成立，新增的热卖商品
                hotListNumsVOS.add(new HotListNumsVO(goods.getGoods(), 0));
            }
            servletContext.setAttribute("hotList", hotListNumsVOS);
        }

        List<Attribute> attributes = goods.getAttributes();
        for (Attribute attribute : attributes) {
            attribute.setUpdateTime(new Date());
            attributeMapper.updateByPrimaryKeySelective(attribute);
        }


        Goods goods1 = goods.getGoods();
        goods1.setUpdateTime(new Date());
        goodsMapper.updateByPrimaryKeySelective(goods1);


        List<Product> products = goods.getProducts();
        for (Product product : products) {
            product.setUpdateTime(new Date());
            productMapper.updateByPrimaryKeySelective(product);
        }

        List<Specification> specifications = goods.getSpecifications();
        for (Specification specification : specifications) {
            specification.setUpdateTime(new Date());
            specificationMapper.updateByPrimaryKeySelective(specification);
        }

    }

    @Override
    public GoodsDetailVo selectDetail(Integer id) {
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();


        //查找market_goods
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        //获取categoryId
        Integer categoryId = goods.getCategoryId();
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        //获取Pid
        Integer pid = category.getPid();
        Integer[] categoryIds = new Integer[2];
        categoryIds[0] = categoryId;
        categoryIds[1] = pid;


        //查找market_attribute
        AttributeExample attributeExample = new AttributeExample();
        AttributeExample.Criteria criteria = attributeExample.createCriteria();
        criteria.andGoodsIdEqualTo(id);
        List<Attribute> attributes = attributeMapper.selectByExample(attributeExample);

        //查找market_specification
        SpecificationExample specificationExample = new SpecificationExample();
        SpecificationExample.Criteria criteria1 = specificationExample.createCriteria();
        criteria1.andGoodsIdEqualTo(id);
        List<Specification> specifications = specificationMapper.selectByExample(specificationExample);

        //查找market_product
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria2 = productExample.createCriteria();
        criteria2.andGoodsIdEqualTo(id);
        List<Product> products = productMapper.selectByExample(productExample);

        GoodsDetailVo goodsDetailVo1 = new GoodsDetailVo(categoryIds, goods, attributes, specifications, products);
        return goodsDetailVo1;
    }

    @Override
    public void deleteGoods(Goods goods) {
//        goods.setDeleted(true);
//        goods.setUpdateTime(new Date());
//        goodsMapper.updateByPrimaryKeySelective(goods);
        goodsMapper.deleteByPrimaryKey(goods.getId());
    }

    @Override
    public WxHomeIndexVo selectIndex(HttpServletRequest req) {


        //新品
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andIsNewEqualTo(true);
        criteria.andDeletedEqualTo(false);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);


        // 优惠券
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria2 = couponExample.createCriteria();
        criteria2.andDeletedEqualTo(false);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        //一级类目
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria3 = categoryExample.createCriteria();
        criteria3.andDeletedEqualTo(false).andLevelEqualTo("L1");
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        // 团购
        GrouponExample grouponExample = new GrouponExample();
        GrouponExample.Criteria criteria4 = grouponExample.createCriteria();
        criteria4.andDeletedEqualTo(false);
        List<Groupon> groupons = grouponMapper.selectByExample(grouponExample);

        //Banner
        AdExample adExample = new AdExample();
        AdExample.Criteria criteria5 = adExample.createCriteria();
        criteria5.andDeletedEqualTo(false).andEnabledEqualTo(true);
        List<Ad> ads = adMapper.selectByExample(adExample);

        //Brand
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria criteria6 = brandExample.createCriteria();
        criteria6.andDeletedEqualTo(false);
        List<Brand> brands = brandMapper.selectByExample(brandExample);

        //热卖
        GoodsExample goodsExample1 = new GoodsExample();
        GoodsExample.Criteria criteria1 = goodsExample1.createCriteria();
        criteria1.andIsHotEqualTo(true).andDeletedEqualTo(false);
        List<Goods> goods1 = goodsMapper.selectByExample(goodsExample1);

        ServletContext servletContext = req.getServletContext();
        Object hotList = servletContext.getAttribute("hotList");
        if(hotList == null){    // 初次访问首页，创建ArrayList记录热卖商品次数
            ArrayList<HotListNumsVO> list = new ArrayList<>();
            for (Goods g : goods1) {
                list.add(new HotListNumsVO(g,0));
            }
            servletContext.setAttribute("hotList",list);  // 查询DB后，保存到Context域

        } else {    // 根据访问次数排序

            ArrayList<HotListNumsVO> numsList = HotGoodsSortUtil.sort((ArrayList<HotListNumsVO>) servletContext.getAttribute("hotList"));
            goods1 = new ArrayList<Goods>();
            for (HotListNumsVO goodsAndNums : numsList) {
                goods1.add(goodsAndNums.getGoods());
            }
        }

        //Topic
        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria7 = topicExample.createCriteria();
        criteria7.andDeletedEqualTo(false);
        List<Topic> topics = topicMapper.selectByExample(topicExample);


        //FloorGoodsList
        //一级类目
        List<Category> categories1 = categoryMapper.selectCategoryLevel();

        List<WxFloorGoodsListVo> floorGoodsListVos = new ArrayList<>();
        Set<WxFloorGoodsListVo> floorGoodsListVoList = new HashSet<>();
        for (Category category : categories1) {
            Integer level1Id = category.getId();
            CategoryExample categoryExample1 = new CategoryExample();
            CategoryExample.Criteria criteria9 = categoryExample1.createCriteria();
            criteria9.andPidEqualTo(level1Id).andDeletedEqualTo(false);
            List<Category> categories2 = categoryMapper.selectByExample(categoryExample1);
            for (Category category1 : categories2) {
                Integer categoryLevel2Id = category1.getId();
                GoodsExample goodsExample2 = new GoodsExample();
                GoodsExample.Criteria criteria8 = goodsExample2.createCriteria();
                criteria8.andCategoryIdEqualTo(categoryLevel2Id).andDeletedEqualTo(false);
                List<Goods> floorGoods = goodsMapper.selectByExample(goodsExample2);
                if (floorGoods.size() != 0) {
                    floorGoodsListVoList.add(new WxFloorGoodsListVo(category.getName(), floorGoods, category.getId()));
                }
            }
        }
        for (WxFloorGoodsListVo wxFloorGoodsListVo : floorGoodsListVoList) {
            floorGoodsListVos.add(new WxFloorGoodsListVo(wxFloorGoodsListVo.getName(), wxFloorGoodsListVo.getGoodsList(), wxFloorGoodsListVo.getId()));
        }


        //market_system
        SystemExample systemExample = new SystemExample();
        List<System> systems = systemMapper.selectByExample(systemExample);
        System system1 = systems.get(1);
        Integer keyValue = Integer.valueOf(system1.getKeyValue());
        System system2 = systems.get(9);
        Integer keyValue2 = Integer.valueOf(system2.getKeyValue());
        System system3 = systems.get(11);
        Integer keyValue11 = Integer.valueOf(system3.getKeyValue());
        System system4 = systems.get(14);
        Integer keyValue14 = Integer.valueOf(system4.getKeyValue());
        System system5 = systems.get(16);
        Integer keyValue16 = Integer.valueOf(system5.getKeyValue());
        System system6 = systems.get(17);
        Integer keyValue17 = Integer.valueOf(system6.getKeyValue());


        List<Goods> goodsList = new ArrayList<>();
        //新品
        for (int i = 0; i < keyValue; i++) {
            Goods goods2 = goods.get(i);
            goodsList.add(goods2);
        }
        //热卖 goods1
        List<Goods> goodsList1 = new ArrayList<>();
        for (Integer i = 0; i < keyValue2; i++) {
            Goods goods2 = goods1.get(i);
            goodsList1.add(goods2);
        }

        //brands
        List<Brand> brandList = new ArrayList<>();
        for (Integer i = 0; i < keyValue16; i++) {
            Brand brand = brands.get(i);
            brandList.add(brand);
        }
        //topics
        List<Topic> topicList = new ArrayList<>();
        for (Integer i = 0; i < keyValue17; i++) {
            Topic topic = topics.get(i);
            topicList.add(topic);
        }
        //catLogList
        List<WxFloorGoodsListVo> wxFloorGoodsListVoList = new ArrayList<>();


        for (Integer i = 0; i < keyValue14; i++) {
            WxFloorGoodsListVo wxFloorGoodsListVo = floorGoodsListVos.get(i);
            List<Goods> goodsList2 = wxFloorGoodsListVo.getGoodsList();
            List<Goods> goodsList3 = new ArrayList<>();
            for (Integer integer = 0; integer < keyValue11; integer++) {
                Goods goods2 = goodsList2.get(integer);
                goodsList3.add(goods2);
            }
            wxFloorGoodsListVo.setGoodsList(goodsList3);
            wxFloorGoodsListVoList.add(wxFloorGoodsListVo);
        }


        WxHomeIndexVo wxHomeIndexVo = new WxHomeIndexVo(goodsList, coupons, categories, groupons, ads, brandList, goodsList1, topicList, wxFloorGoodsListVoList);

        return wxHomeIndexVo;
    }

    @Override
    public BasePageData selectGoodsCategory(String keyword, Boolean isNew, Boolean isHot, Integer page, Integer limit, String sort, String order, Integer categoryId) {
        if (categoryId != null && categoryId != 0) {
            PageHelper.startPage(page, limit);
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria criteria1 = goodsExample.createCriteria();

            criteria1.andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);

            List<Goods> goods2 = goodsMapper.selectByExample(goodsExample);

            List<Category> categories1 = categoryMapper.selectCategoryLevel2();

            return BasePageData.ok2(goods2, categories1);
        }
        if (keyword != null && isHot == null && isNew == null) {

            //更新搜索历史
            SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
            SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
            criteria.andKeywordEqualTo(keyword).andDeletedEqualTo(false);
            List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);

            //如果搜索历史存在则根据，搜索历史更行搜索时间，
            if (searchHistories != null && searchHistories.size() > 0) {
                SearchHistory searchHistory = searchHistories.get(0);
                searchHistory.setAddTime(new Date());
                searchHistoryMapper.updateByPrimaryKeySelective(searchHistory);
            } else {
                //如果不存在则插入搜索历史时间
                //如果当前用户已经登录则记录到搜索历史当中
                Subject subject = SecurityUtils.getSubject();
                User user = (User) subject.getPrincipal();
                if (user != null) {
                    Integer userId = user.getId();
                    //添加搜索历史
                    SearchHistory searchHistory = new SearchHistory();
                    searchHistory.setUserId(userId);
                    searchHistory.setKeyword(keyword);
                    searchHistory.setFrom("wx");
                    searchHistory.setAddTime(new Date());
                    searchHistory.setUpdateTime(new Date());
                    searchHistory.setDeleted(false);
                    //执行
                    searchHistoryMapper.insert(searchHistory);
                }

            }

            //TODO 此处有待强化
            //根据搜索关键词以及分页查询关查询商品
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
            //配置分页信息
            PageHelper.startPage(page, limit);

            if (CommonUtil.isStrNotEmpty(keyword)) {
                goodsExampleCriteria.andNameLike("%" + keyword + "%");
            }
            if (categoryId != null && categoryId > 0) {
                goodsExampleCriteria.andCategoryIdEqualTo(categoryId);
            }
            criteria.andDeletedEqualTo(false);
            //添加排序条件
            goodsExample.setOrderByClause(sort + " " + order);
            //执行
            List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);


            //根据商品中的id查询对应分类信息
            List<Category> filterCategoryList = null;
            if (goodsList != null && goodsList.size() > 0) {
                ArrayList<Integer> goodsIdList = new ArrayList<>();
                for (Goods good : goodsList) {
                    Integer categoryIdInGoods = good.getCategoryId();
                    if (!goodsIdList.contains(categoryIdInGoods)) {
                        goodsIdList.add(good.getCategoryId());
                    }
                }
                //根据类目id查询分类
                CategoryExample categoryExample = new CategoryExample();
                CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
                categoryExampleCriteria.andIdIn(goodsIdList).andDeletedEqualTo(false);
                filterCategoryList = categoryMapper.selectByExample(categoryExample);
            }
//            BasePageData basePageData = BasePageData.ok(goodsList);
//            //赋值
//            SearchGoodsPageDataVo searchGoodsPageDataVo = new SearchGoodsPageDataVo();
//            searchGoodsPageDataVo.setLimit(basePageData.getLimit());
//            searchGoodsPageDataVo.setPage(basePageData.getPage());
//            searchGoodsPageDataVo.setPages(basePageData.getPages());
//            searchGoodsPageDataVo.setTotal(basePageData.getTotal());
//            searchGoodsPageDataVo.setList(basePageData.getList());
//            searchGoodsPageDataVo.setFilterCategoryList(categoryList);
            //响应结果
            return BasePageData.ok2(goodsList, filterCategoryList);
        }

        if (isNew == null) {
            PageHelper.startPage(page, limit);
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria criteria = goodsExample.createCriteria();

            criteria.andIsHotEqualTo(isHot).andDeletedEqualTo(false);
            goodsExample.setOrderByClause(sort + " " + order);
            Set<Category> categoriesList = new HashSet<>();
            List<Category> filterCategoryList = new ArrayList<>();
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            for (Goods good : goods) {
                Integer goodCategoryId = good.getCategoryId();
                CategoryExample categoryExample = new CategoryExample();
                CategoryExample.Criteria criteria1 = categoryExample.createCriteria();
                criteria1.andIdEqualTo(goodCategoryId).andDeletedEqualTo(false);
                List<Category> categories = categoryMapper.selectByExample(categoryExample);
                for (Category category : categories) {
                    categoriesList.add(new Category(category.getId(), category.getName(), category.getKeywords(), category.getDesc(), category.getPid(), category.getIconUrl(), category.getPicUrl(), category.getLevel(), category.getSortOrder(), category.getAddTime(), category.getUpdateTime(), category.getDeleted()));
                }
            }
            for (Category category : categoriesList) {
                filterCategoryList.add(new Category(category.getId(), category.getName(), category.getKeywords(), category.getDesc(), category.getPid(), category.getIconUrl(), category.getPicUrl(), category.getLevel(), category.getSortOrder(), category.getAddTime(), category.getUpdateTime(), category.getDeleted()));
            }
            return BasePageData.ok2(goods, filterCategoryList);

        }
        if (isHot == null) {
            PageHelper.startPage(page, limit);
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria criteria = goodsExample.createCriteria();

            criteria.andIsNewEqualTo(isNew).andDeletedEqualTo(false);
            goodsExample.setOrderByClause(sort + " " + order);
            List<Category> filterCategoryList = new ArrayList<>();
            Set<Category> categoriesList = new HashSet<>();
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            for (Goods good : goods) {
                Integer goodCategoryId = good.getCategoryId();
                CategoryExample categoryExample = new CategoryExample();
                CategoryExample.Criteria criteria1 = categoryExample.createCriteria();
                criteria1.andIdEqualTo(goodCategoryId).andDeletedEqualTo(false);
                List<Category> categories = categoryMapper.selectByExample(categoryExample);
                for (Category category : categories) {
                    categoriesList.add(new Category(category.getId(), category.getName(), category.getKeywords(), category.getDesc(), category.getPid(), category.getIconUrl(), category.getPicUrl(), category.getLevel(), category.getSortOrder(), category.getAddTime(), category.getUpdateTime(), category.getDeleted()));
                }
            }
            for (Category category : categoriesList) {
                filterCategoryList.add(new Category(category.getId(), category.getName(), category.getKeywords(), category.getDesc(), category.getPid(), category.getIconUrl(), category.getPicUrl(), category.getLevel(), category.getSortOrder(), category.getAddTime(), category.getUpdateTime(), category.getDeleted()));
            }

            return BasePageData.ok2(goods, filterCategoryList);

        }
        return null;
    }

    @Override
    public WxCategoryListVo selectCategoryList(Integer id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        String level = category.getLevel();
        if ("L1".equals(level)) {
            CategoryExample categoryExample2 = new CategoryExample();
            CategoryExample.Criteria criteria2 = categoryExample2.createCriteria();
            criteria2.andPidEqualTo(id).andDeletedEqualTo(false);
            List<Category> categories = categoryMapper.selectByExample(categoryExample2);
            Category category1 = categories.get(0);

            WxCategoryListVo wxCategoryListVo = new WxCategoryListVo(category1, categories, category);
            return wxCategoryListVo;
        }
        if ("L2".equals(level)) {
            Integer pid = category.getPid();
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria criteria = categoryExample.createCriteria();
            criteria.andPidEqualTo(pid).andDeletedEqualTo(false);
            List<Category> categories = categoryMapper.selectByExample(categoryExample);
            Category category1 = categoryMapper.selectByPrimaryKey(pid);

            WxCategoryListVo wxCategoryListVo = new WxCategoryListVo(category, categories, category1);
            return wxCategoryListVo;
        }
        return null;
    }

    @Override
    public WxDetailVo selectWxDetail(HttpServletRequest req, Integer id) {

        // 增加访问次数，重新保存到Context
        ServletContext servletContext = req.getServletContext();
        Object hotList = servletContext.getAttribute("hotList");
        if(hotList != null){
            ArrayList<HotListNumsVO> hotListNumsVOS = (ArrayList<HotListNumsVO>) hotList;
            HotListNumsVO hotListNumsVO = null;
            for (HotListNumsVO vo : hotListNumsVOS) {   // 查询是否是热卖商品
                if(vo.getGoods().getId().equals(id)){   //
                    hotListNumsVO = vo;
                }
            }
            if(hotListNumsVO != null){  // 不为null，说明是热卖商品
                hotListNumsVO.setNums(hotListNumsVO.getNums() + 1);
                servletContext.setAttribute("hotList", hotListNumsVOS);
            }
        }

        //specificationList
        SpecificationExample specificationExample = new SpecificationExample();
        SpecificationExample.Criteria criteria = specificationExample.createCriteria();
        criteria.andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<Specification> specifications = specificationMapper.selectByExample(specificationExample);
        List<WxSpecificationVo> wxSpecificationVo = new ArrayList<>();

        for (Specification specification1 : specifications) {
            String name = specification1.getSpecification();
//            wxSpecificationVo.add(new WxSpecificationVo(name , specifications));
            List<Specification> specificationList = new ArrayList<>();
            specificationList.add(new Specification(specification1.getId(), specification1.getGoodsId(), specification1.getSpecification(), specification1.getValue(), specification1.getPicUrl(), specification1.getAddTime(), specification1.getUpdateTime(), specification1.getDeleted()));
            wxSpecificationVo.add(new WxSpecificationVo(name, specificationList));
        }


        //grouponList
        GrouponExample grouponExample = new GrouponExample();
        GrouponExample.Criteria grouponExampleCriteria = grouponExample.createCriteria();
        grouponExampleCriteria.andDeletedEqualTo(false);
        List<Groupon> groupons = grouponMapper.selectByExample(grouponExample);

        //issueList
        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria issueExampleCriteria = issueExample.createCriteria();
        issueExampleCriteria.andDeletedEqualTo(false);
        List<Issue> issues = issueMapper.selectByExample(issueExample);

        //shareImage
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        String shareImage = goods.getShareUrl();

        //comment
        Integer count = 0;
        WxCommentVo wxCommentVo = new WxCommentVo();

        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria criteria2 = commentExample.createCriteria();
        criteria2.andValueIdEqualTo(id).andDeletedEqualTo(false).andTypeEqualTo(((byte) 0));
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        count = comments.size();
        WxCommentVo comment = new WxCommentVo(comments , count);



        //attribute
        AttributeExample attributeExample = new AttributeExample();
        AttributeExample.Criteria attributeExampleCriteria = attributeExample.createCriteria();
        attributeExampleCriteria.andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<Attribute> attributes = attributeMapper.selectByExample(attributeExample);

        //brand
        Integer brandId = goods.getBrandId();
        Brand brand = brandMapper.selectByPrimaryKey(brandId);

        //productList
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria productExampleCriteria = productExample.createCriteria();
        productExampleCriteria.andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<Product> products = productMapper.selectByExample(productExample);


        //userHasCollect
        Byte userHasCollect = 0;
        //获取当前用户id
        Subject subject = SecurityUtils.getSubject();
        User primaryPrincipal = null;
        try {
            primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
        } catch (Exception e) {
            CollectExample collectExample = new CollectExample();
            CollectExample.Criteria criteria1 = collectExample.createCriteria();
            criteria1.andValueIdEqualTo(id);
            List<Collect> collects = collectMapper.selectByExample(collectExample);
            if (collects.size() != 0) {
                Collect collect = collects.get(0);
                Boolean deleted = collect.getDeleted();
                if (!deleted) {
                    userHasCollect = 1;
                    WxDetailVo wxDetailVo = new WxDetailVo(wxSpecificationVo, groupons, issues, userHasCollect, shareImage, comment, true, attributes, brand, products, goods);
                    return wxDetailVo;
                } else {
                    userHasCollect = 0;
                    WxDetailVo wxDetailVo = new WxDetailVo(wxSpecificationVo, groupons, issues, userHasCollect, shareImage, comment, true, attributes, brand, products, goods);
                    return wxDetailVo;
                }
            }
            userHasCollect = 0;
            WxDetailVo wxDetailVo = new WxDetailVo(wxSpecificationVo, groupons, issues, userHasCollect, shareImage, comment, true, attributes, brand, products, goods);
            return wxDetailVo;
        }
        Integer userId = primaryPrincipal.getId();

        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria1 = collectExample.createCriteria();
        criteria1.andValueIdEqualTo(id).andUserIdEqualTo(userId);
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        if (collects.size() != 0) {
            Collect collect = collects.get(0);
            Boolean deleted = collect.getDeleted();
            if (!deleted) {
                userHasCollect = 1;
                WxDetailVo wxDetailVo = new WxDetailVo(wxSpecificationVo, groupons, issues, userHasCollect, shareImage, comment, true, attributes, brand, products, goods);
                return wxDetailVo;
            } else {
                userHasCollect = 0;
                WxDetailVo wxDetailVo = new WxDetailVo(wxSpecificationVo, groupons, issues, userHasCollect, shareImage, comment, true, attributes, brand, products, goods);
                return wxDetailVo;
            }
        }

        userHasCollect = 0;
        WxDetailVo wxDetailVo = new WxDetailVo(wxSpecificationVo, groupons, issues, userHasCollect, shareImage, comment, true, attributes, brand, products, goods);
        return wxDetailVo;
    }

    @Override
    public BasePageData selectWxRelated(Integer id) {

        Goods goods = goodsMapper.selectByPrimaryKey(id);
        Integer categoryId = goods.getCategoryId();
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
        List<Goods> goods1 = goodsMapper.selectByExample(goodsExample);

        return BasePageData.ok1(goods1);
    }


//    @Override
//    public SearchGoodsPageDataVo searchGoods(String keyword, Integer categoryId, BaseParam param) {
//        //更新搜索历史
//        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
//        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
//        criteria.andKeywordEqualTo(keyword).andDeletedEqualTo(false);
//        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
//
//        //如果搜索历史存在则根据，搜索历史更行搜索时间，
//        if (searchHistories != null && searchHistories.size() > 0) {
//            SearchHistory searchHistory = searchHistories.get(0);
//            searchHistory.setAddTime(new Date());
//            searchHistoryMapper.updateByPrimaryKeySelective(searchHistory);
//        } else {
//            //如果不存在则插入搜索历史时间
//            //如果当前用户已经登录则记录到搜索历史当中
//            Subject subject = SecurityUtils.getSubject();
//            User user = (User) subject.getPrincipal();
//            if (user != null) {
//                Integer userId = user.getId();
//                //添加搜索历史
//                SearchHistory searchHistory = new SearchHistory();
//                searchHistory.setUserId(userId);
//                searchHistory.setKeyword(keyword);
//                searchHistory.setFrom("wx");
//                searchHistory.setAddTime(new Date());
//                searchHistory.setUpdateTime(new Date());
//                searchHistory.setDeleted(false);
//                //执行
//                searchHistoryMapper.insert(searchHistory);
//            }
//
//        }
//
//        //TODO 此处有待强化
//        //根据搜索关键词以及分页查询关查询商品
//        GoodsExample goodsExample = new GoodsExample();
//        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
//        //配置分页信息
//        PageHelper.startPage(param.getPage(), param.getLimit());
//
//        if (CommonUtil.isStrNotEmpty(keyword)) {
//            goodsExampleCriteria.andNameLike("%" + keyword + "%");
//        }
//        if (categoryId != null && categoryId > 0) {
//            goodsExampleCriteria.andCategoryIdEqualTo(categoryId);
//}
//        criteria.andDeletedEqualTo(false);
//                //添加排序条件
//                goodsExample.setOrderByClause(param.getSort() + " " + param.getOrder());
//                //执行
//                List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
//
//
//        //根据商品中的id查询对应分类信息
//        List<Category> categoryList = null;
//        if (goodsList != null && goodsList.size() > 0) {
//        ArrayList<Integer> goodsIdList = new ArrayList<>();
//        for (Goods good : goodsList) {
//        Integer categoryIdInGoods = good.getCategoryId();
//        if (!goodsIdList.contains(categoryIdInGoods)) {
//        goodsIdList.add(good.getCategoryId());
//        }
//        }
//        //根据类目id查询分类
//        CategoryExample categoryExample = new CategoryExample();
//        CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
//        categoryExampleCriteria.andIdIn(goodsIdList).andDeletedEqualTo(false);
//        categoryList = categoryMapper.selectByExample(categoryExample);
//        }
//        BasePageData basePageData = BasePageData.ok(goodsList);
//        //赋值
//        SearchGoodsPageDataVo searchGoodsPageDataVo = new SearchGoodsPageDataVo();
//        searchGoodsPageDataVo.setLimit(basePageData.getLimit());
//        searchGoodsPageDataVo.setPage(basePageData.getPage());
//        searchGoodsPageDataVo.setPages(basePageData.getPages());
//        searchGoodsPageDataVo.setTotal(basePageData.getTotal());
//        searchGoodsPageDataVo.setList(basePageData.getList());
//        searchGoodsPageDataVo.setFilterCategoryList(categoryList);
//        //响应结果
//        return searchGoodsPageDataVo;
//        }
}
